package com.houkunlin.wake.lan.host;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Service：主机信息
 *
 * @author HouKunLin
 * @date 2021-08-13 23:25:23
 */
@CacheConfig(cacheNames = {HostInfoService.CACHE_NAME})
@Transactional(rollbackFor = Exception.class)
@Service
@AllArgsConstructor
public class HostInfoServiceImpl extends ServiceImpl<HostInfoRepository, HostInfo> implements HostInfoService {
    private final HostInfoTransform hostInfoTransform;

    @Override
    public HostInfo saveHostInfo(HostInfoForm form) {
        final HostInfo info = lambdaQuery().eq(HostInfo::getMac, form.getMac()).one();
        final HostInfo hostInfo;
        if (info != null) {
            hostInfo = hostInfoTransform.toEntity(form, info);
        } else {
            hostInfo = hostInfoTransform.toEntity(form);
        }
        saveOrUpdate(hostInfo);
        return hostInfo;
    }

    @Override
    public String deleteHostInfo(Set<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return null;
        }
        final List<HostInfo> list = lambdaQuery().select(HostInfo::getId).in(HostInfo::getId, ids).list();
        if (!list.isEmpty()) {
            removeByIds(list.stream().map(HostInfo::getId).collect(Collectors.toList()));
        }
        return list.stream().map(HostInfo::getId).collect(Collectors.joining("、"));
    }
}
